package com.example.chapter3_1.controller;

import com.example.chapter3_1.entity.User;
import com.example.chapter3_1.service.LoginService;
import com.example.chapter3_1.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Controller
public class UserContorller {
    //打开主页
    @RequestMapping(value = {"/index","/main"})
    public String index(){
        log.info("打开主页");
        return "index";
    }
    //打开登陆界面
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView showlogin(ModelAndView mv){
        log.info("打开登陆界面");
        mv.setViewName("login");
        return mv;
    }
    
//    @RequestMapping(value = "/userlogin")
//    public String userlogin(){
//        return "forward:/index.html";
//    }

    //登陆验证
    @Autowired
    @Qualifier("loginServiceIml")
    private LoginService loginService;
    @RequestMapping(value = "/login",name = "登陆验证", method = RequestMethod.POST)
    public ModelAndView userlogin(ModelAndView mv,User user){
        if (loginService.login(user.getName(),user.getPassword())){
            log.info("跳转到主页");
            mv.setViewName("index");
            mv.addObject("user",user);
        }else {
            mv.setViewName("login");
            mv.addObject("error","登陆失败");
        }
        return mv;
    }

    @Autowired
    private UserService userService;

    //响应用户访问注册界面的请求
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public ModelAndView showregister(ModelAndView modelAndView){
        User user = new User();
        //添加实体类对象
        modelAndView.addObject("user",user);
        //指定跳转的页面
        modelAndView.setViewName("register");
        return modelAndView;
    }

    //接受注册请求
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public ModelAndView handleregister(ModelAndView modelAndView,User user){
        //验证用户名是否存在
        try {
            userService.register(user);
            modelAndView.addObject("success","注册成功");
            modelAndView.setViewName("register");  // 设置视图名称，继续显示注册页面
        } catch (Exception e) {
            modelAndView.addObject("error",e.getMessage());
            modelAndView.setViewName("register");  // 发生错误时也显示注册页面
        }
        return modelAndView;
    }
}
